package com.ndp.fb.rdb.db.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.ndp.fb.rdb.api.EcTrackingProfilesRdbService;
import com.ndp.fb.rdb.db.DaoTemplate;
import com.ndp.fb.rdb.db.impl.mapper.DefaultRowMapper;
import com.ndp.fb.rdb.model.EcTrackingProfiles;

import java.util.List;

/**
 * Created by jacky.cheng on 2016/6/29.
 */
@Service
public class EcTrackingProfilesRdbServiceImpl extends DaoTemplate implements EcTrackingProfilesRdbService {

    @Override
    public Long findProfileId(String trackingId, int offset) {
        String sql = "SELECT profile_id FROM ec_tracking_profiles WHERE tracking_id = '"+trackingId+"' and timezone= "+offset;
        return getJdbcTemplate().queryForLong(sql);
    }
    @Override
    public EcTrackingProfiles findByTrackingIdAndProfileId(String trackingId, Long profileId) {
        String sql = "SELECT * FROM ec_tracking_profiles WHERE tracking_id = ? and profile_id=?";
        return findOne(sql, new Object[]{trackingId, profileId}, DefaultRowMapper.autoRowMapper(EcTrackingProfiles.class));
    }

    @Override
    public List<Long> findProfileIds(String trackingId) {
        String sql = "SELECT profile_id FROM ec_tracking_profiles WHERE tracking_id =?";
        return getJdbcTemplate().queryForList(sql, new Object[]{trackingId}, Long.class);
    }

    @Override
    public List<Long> findProfileIdsByProductIdAndTimeZone(Long productId, int offset) {
        String sql = "SELECT t.profile_id FROM `ec_ga_credential` c, ec_tracking_profiles t " +
                "WHERE c.tracking_id=t.tracking_id and c.product_id=? and t.timezone= ?";
       return  getJdbcTemplate().queryForList(sql, new Object[]{productId, offset}, Long.class);
    }

    @Override
    public void saveProfileIdAndTrackId(String track_id, Long profileId, int offset) {
        EcTrackingProfiles t = findByTrackingIdAndProfileId(track_id, profileId);
        if (t != null) {
            String sql = "UPDATE `ec_tracking_profiles` " +
                    "SET `timezone`=? " +
                    "WHERE (`id`=?);";
            getJdbcTemplate().update(sql,offset, t.getId());
        }else {
            EcTrackingProfiles p = new EcTrackingProfiles();
            p.setTrackingId(track_id);
            p.setProfileId(profileId);
            p.setTimezone(offset);
            saveResultId(p);
        }
    }
}